#include "HelloWorldScene.h"
#include "GameScene.h"
//#include "./tinyxml/tinyxml.h"
#include "Util.h"
#include "GameManager.h"
#include "Editor.h"

USING_NS_CC;
USING_NS_CC_EXT; 
using namespace tinyxml2;

static int pagenum = 3;

CCScene* HelloWorld::scene()
{
    // 'scene' is an autorelease object
    CCScene *scene = CCScene::create();
    
    // 'layer' is an autorelease object
    HelloWorld *layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !CCLayer::init() )
    {
        return false;
    }
    
    CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
    CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();


    /*CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
                                        "CloseNormal.png",
                                        "CloseSelected.png",
                                        this,
										menu_selector(HelloWorld::startGame));
                                        //menu_selector(HelloWorld::menuCloseCallback));
	pCloseItem->setTag(1);
	pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 ,
                                origin.y + pCloseItem->getContentSize().height/2));
    CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
    pMenu->setPosition(CCPointZero);
    this->addChild(pMenu, 1);

    
    CCLabelTTF* pLabel = CCLabelTTF::create("Hello World", "Arial", 24);
    pLabel->setPosition(ccp(origin.x + visibleSize.width/2,
                            origin.y + visibleSize.height - pLabel->getContentSize().height));
    this->addChild(pLabel, 1);

    CCSprite* pSprite = CCSprite::create("HelloWorld.png");
    pSprite->setPosition(ccp(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));
	hello = pSprite;
    this->addChild(pSprite, 0);*/

	CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true);

	std::string fullPath = CCFileUtils::sharedFileUtils()->fullPathForFilename("maze.xml");  
	tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument();  
	xmlDoc->LoadFile(fullPath.c_str());
	XMLElement* rootElement = xmlDoc->RootElement();
	XMLElement* levelElement = rootElement->FirstChildElement();  
	int levelidx = 1;
	while(levelElement)
	{
		MazeInfo *mi = new MazeInfo;
		mi->level = levelidx; //atoi(levelElement->Attribute("id"));
		mi->steps = atoi(levelElement->Attribute("steps"));
		mi->stepInfo.resize(mi->steps);
		mi->columns = atoi(levelElement->Attribute("columns"));
		std::string ques = levelElement->Attribute("questions");
		std::vector<std::string> qv = stringsplit(ques, '|');
		for (int i=0; i< qv.size(); i++)
		{
			mi->questions.push_back(qv[i]);
		}

		XMLElement *stepEle = levelElement->FirstChildElement();
		int cstep = 0;

		while (stepEle)
		{
			std::string options = stepEle->Attribute("options");					
			std::vector<std::string> ov = stringsplit(options, '|');
			for (int i=0; i< ov.size(); i++)
			{
				mi->stepInfo[cstep].push_back(ov[i]);
			}
			
			stepEle = stepEle->NextSiblingElement();
			++cstep;
		}
		levelElement = levelElement->NextSiblingElement();
		g_maze[levelidx++] = mi;
	}
	delete xmlDoc;

	//CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("main.plist");
	CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("basketball.plist");
	//todo remove it
    CCUserDefault::sharedUserDefault()->setIntegerForKey("level",1);

	page = 1;
	displayLevelLayer();
    return true;
}

void HelloWorld::generateOptions()
{
	/*string fullPath = CCFileUtils::sharedFileUtils()->fullPathForFilename("basketball.plist");
	CCDictionary* plistDic = CCDictionary::createWithContentsOfFile(fullPath.c_str());  
	CCDictionary* framesDic = dynamic_cast<CCDictionary*>(plistDic->objectForKey("frames"));  
	CCArray * names = framesDic->allKeys();
	names->retain();

	std::string fullPath = CCFileUtils::sharedFileUtils()->fullPathForFilename("basketball.xml");  
	tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument();  
	xmlDoc->LoadFile(fullPath.c_str());
	XMLElement* rootElement = xmlDoc->RootElement();
	XMLElement* levelElement = rootElement->FirstChildElement();  
	int levelidx = 1;
	while(levelElement)
	{
		int steps = atoi(levelElement->Attribute("steps"));
		int columns = atoi(levelElement->Attribute("columns"));
		std::string ques = levelElement->Attribute("questions");
		for (int i=1; i<=steps; ++i)
		{
			 XMLElement *stepElement = new XMLElement("Step");
			 std::stringstream opt;
			 for (int k=0; k<8; ++k)
			 {
				 string s;
				 if(k != 7)
					 opt<<s<<"|";
				 else
					 opt<<s;
			 }
			 stepElement->SetAttribute("options", opt.str().c_str());
		}
		XMLElement *stepEle = levelElement->FirstChildElement();
		levelElement = levelElement->NextSiblingElement();
	}*/
}

void HelloWorld::displayLevelLayer()
{
	CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
	CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();

	// CCScrollView
	int page = 1;
	scrollView = CCScrollView::create();
	CCLayer *layer = CCLayer::create();
	//CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(layer, 0, false);
	CCSpriteFrameCache *cache =  CCSpriteFrameCache::sharedSpriteFrameCache();
	cache->addSpriteFrame(CCSpriteFrame::create("border.png", CCRectMake(0,0,88,87)), "border.png");
	cache->addSpriteFrame(CCSpriteFrame::create("border2.png", CCRectMake(0,0,85,85)), "border2.png");
	cache->addSpriteFrame(CCSpriteFrame::create("Help_Point01.png",CCRectMake(0,0,32,32)),"Help_Point01.png");
	cache->addSpriteFrame(CCSpriteFrame::create("Help_Point02.png",CCRectMake(0,0,32,32)),"Help_Point02.png");
	for (int i=0; i<3; ++i)
	{
		for (int j=1; j<=20; ++j)
		{
			char t[1024];
			snprintf(t, sizeof(t), "%d", j+20*i);
			CCLabelTTF* pLabel = CCLabelTTF::create(t, "Arial", 24);
			int x = origin.x + visibleSize.width / 5 * ((j-1)%4 + 1) + i * visibleSize.width;
			int y = origin.y + (visibleSize.height - 100 )/5 * (5 -  (j-1)/4);
			pLabel->setPosition(ccp(x, y));
			layer->addChild(pLabel, 1);

			 //CCSprite *bg = CCSprite::createWithSpriteFrameName("border2.png");
			 //bg->setPosition(ccp(x,y));
			 //layer->addChild(bg, 0);
			 CCMenuItemImage *bg =  CCMenuItemImage::create("border2.png", "border2.png", this, menu_selector(HelloWorld::startGame));
			 bg->setTag(j+20*i);
			 CCMenu* pMenu = CCMenu::create(bg, NULL);
			 pMenu->setPosition(ccp(x,y));
			 layer->addChild(pMenu, 0);
		}

		CCSprite *point = CCSprite::createWithSpriteFrameName("Help_Point01.png");
		point->setTag(100+i+1);
		point->setPosition(ccp(visibleSize.width/2 + 40*(i-1), 30));
		this->addChild(point);
	}

	//layer->setAnchorPoint(CCPointZero);
	layer->setPosition(CCPointZero);
	scrollView->setPosition(CCPointZero);
	scrollView->setContentOffset(CCPointZero);
	layer->setContentSize(CCSizeMake(320*pagenum, 480));
	scrollView->setViewSize(CCSizeMake(320, 480));
	scrollView->setContainer(layer);
	scrollView->setTouchEnabled(false);
	scrollView->setDelegate(this);
	scrollView->setDirection(kCCScrollViewDirectionHorizontal);

	addChild(scrollView);

	CCSprite *point = (CCSprite *)this->getChildByTag(101);
	point->setDisplayFrame(cache->spriteFrameByName("Help_Point02.png"));
}


bool HelloWorld::ccTouchBegan(CCTouch* touch, CCEvent* event)
{  
	CCLog("touch begin");
	touchPoint = CCDirector::sharedDirector()->convertToGL(touch->getLocationInView());
	 return true;
}

void HelloWorld::ccTouchMoved(CCTouch* touch, CCEvent* event)
{

}

void HelloWorld::ccTouchEnded(CCTouch* touch, CCEvent* event)
{
	CCPoint endPoint = CCDirector::sharedDirector()->convertToGL(touch->getLocationInView());
	adjustScrollView(endPoint.x-touchPoint.x);
}

void HelloWorld::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent)
{
	CCPoint endPoint = CCDirector::sharedDirector()->convertToGL(pTouch->getLocationInView());
	adjustScrollView(endPoint.x-touchPoint.x);
}


void HelloWorld::menuCloseCallback(CCObject* pSender)
{
    CCDirector::sharedDirector()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
}

void HelloWorld::startGame(CCObject* pSender)
{
	//CCScene  *gs = GameScene::create();
	int l = ((CCNode *)pSender)->getTag();
	CCLog("start game %d", l);
	if (g_maze.find(l) == g_maze.end())
		return;
	
	CCScene *scene = CCScene::create();
	GameScene *layer = new GameScene;
	layer->level = l;
	layer->init();
	scene->addChild(layer);
	/*Editor *ed = new Editor;
	ed->init();
	scene->addChild(layer);
	layer->autorelease();*/
	CCDirector::sharedDirector()->pushScene(scene);
}

void HelloWorld::scrollViewDidScroll(CCScrollView* view)
{

}

void HelloWorld::scrollViewDidZoom(CCScrollView* view)
{

}

void HelloWorld::adjustScrollView(float offset)
{
	if(fabs(offset)<50) {
		CCLog("scroll offset small");
		return;
	}
	CCSize size =CCDirector::sharedDirector()->getWinSize();
	CCSpriteFrameCache *cache =  CCSpriteFrameCache::sharedSpriteFrameCache();
	CCSprite *point = (CCSprite *)this->getChildByTag(100+page);
	point->setDisplayFrame(cache->spriteFrameByName("Help_Point01.png"));
	if (offset<0)
	{
		page ++;

	}else
	{
		page --;
	}

	if (page <1)
	{
		page = 1;
	}else if(page > pagenum)
	{
		page = pagenum;
	}

	point = (CCSprite *)this->getChildByTag(100+page);
	point->setDisplayFrame(cache->spriteFrameByName("Help_Point02.png"));

	CCPoint  adjustPos = ccp(-size.width*(page-1), 0);
	scrollView->setContentOffsetInDuration(adjustPos, 1);
}
